from rest_framework import serializers
from users.models import *
import re
from SxShop3.settings import REGEX_MOBILE
from datetime import datetime, timedelta
from rest_framework.validators import UniqueValidator


# 手机号序列化
class SmsSerializer(serializers.Serializer):

    mobile = serializers.CharField(max_length=11)

    # 验证手机号
    def validate_mobile(self, mobile):

        # 手机号是否已注册
        if UserProfile.objects.filter(mobile=mobile).count():
            raise serializers.ValidationError('手机号已注册')
        # 手机号是否合法
        if not re.match(REGEX_MOBILE, mobile):
            raise serializers.ValidationError('手机号不是正常的手机号')
        # 1分钟内又没有收到过
        one_ago = datetime.now() - timedelta(hours=0, minutes=1, seconds=0)
        if VerifyCode.objects.filter(mobile=mobile, add_time__gt=one_ago):
            raise serializers.ValidationError('距离上一次发送未超过60秒')
        # 验证合法后返回序列化后的手机号
        return mobile


class UserDetailSerializer(serializers.ModelSerializer):
    """
        用户详情序列化类
    """
    class Meta:
        model = UserProfile
        fields = ('name', 'gender', 'birthday', 'email', 'mobile')


# 用户模型序列化
class UserRegSerializer(serializers.ModelSerializer):

    username = serializers.CharField(required=True, allow_blank=False,
                                     validators=[UniqueValidator(queryset=UserProfile.objects.all(),
                                                                 message='用户名已注册')])
    code = serializers.CharField(write_only=True, required=True, allow_blank=False,
                                 max_length=4, min_length=4)

    password = serializers.CharField(write_only=True, style={'input_type': 'password'})

    # 对密码加密
    def create(self, validated_data):
        user = super().create(validated_data=validated_data)
        user.set_password(validated_data['password'])
        user.save()
        return user

    # 对验证码进一步验证
    def validate_code(self, code):

        records = VerifyCode.objects.filter(mobile=self.initial_data['username']).order_by('-add_time')
        # 要注册的用户是否收到过验证码
        if records:
            # 验证码是否超过5分钟
            record = records[0]
            five_ago = datetime.now() - timedelta(hours=0, minutes=5, seconds=0)
            if record.add_time < five_ago:
                raise serializers.ValidationError('验证码过期')
            # 验证码是否正确
            if record.code != code:
                raise serializers.ValidationError('验证码错误')
        else:
            raise serializers.ValidationError('此手机号没有收到过验证码')

    def validate(self, attrs):
        del attrs['code']
        attrs['mobile'] = attrs['username']
        return attrs

    class Meta:
        model = UserProfile
        fields = ('username', 'code', 'mobile', 'password')







